<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <!-- 查询栏 -->
      <div class="table-page-search-wrapper">
        <a-form
          layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="角色名称" name="id" :rules="[{ required: true, message: '请输入角色名称' }]">
                <a-input v-model="queryParam.name" placeholder="请输入" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="状态">
                <a-select v-model="queryParam.status" placeholder="请选择" default-value="0">
                  <a-select-option value="0">全部</a-select-option>
                  <a-select-option value="1">启用</a-select-option>
                  <a-select-option value="2">禁用</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button
                  type="primary"
                  html-type="submit"
                  @click.stop.prevent="handleSearch()"
                >查询</a-button>
                <a-button style="margin-left: 8px" @click="() => this.queryParam = {}">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <!-- 操作栏 -->
      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd({parentId: 0})">新增角色
        </a-button>
      </div>

      <s-table
        size="default"
        ref="table"
        row-key="id"
        :columns="columns"
        :data="loadData"
        :single-data="loadSingleData"
        :scroll="{ x: true }"
        :indent-size="10">
        <span slot="status" slot-scope="text">
          <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
        </span>
        <span slot="createTime" slot-scope="text">{{ text | moment }}</span>
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleChangeStatus(record)">{{ record.status === 1 ? '禁用' : '启用' }}</a>
          <a-divider type="vertical" />
          <a @click="handleDelete(record)">删除</a>
        </span>
      </s-table>

      <!-- 添加角色 -->
      <a-modal
        title="添加角色"
        style="top: 20px;"
        :width="800"
        v-model="addVisible"
        @ok="handleOk($event, 'add')"
      >
        <a-form class="permission-form" :form="form">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="ID"
            hasFeedback
            validateStatus="success"
            hidden="hidden"
          >
            <a-input
              placeholder="ID"
              disabled="disabled"
              v-decorator="['id']"
            />
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="角色名称"
            hasFeedback
          >
            <a-input
              placeholder="角色名称"
              v-decorator="['name', {rules: [{ required: true, message: '角色名称为必填项' }], validateTrigger: ['change', 'blur']}]"
            />
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="角色别名"
            hasFeedback
          >
            <a-input
              placeholder="角色别名"
              v-decorator="['alias', {rules: [{ required: false }], validateTrigger: ['change', 'blur']}]"
            />
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="序号"
            hasFeedback
          >
            <a-input
              placeholder="序号"
              v-decorator="['sort', {rules: [{ required: false }], validateTrigger: ['change', 'blur']}]"
            />
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="状态"
            hasFeedback
          >
            <a-select v-decorator="['status', { initialValue: 1 }]">
              <a-select-option :value="1">正常</a-select-option>
              <a-select-option :value="2">禁用</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="备注"
            hasFeedback
          >
            <a-input
              placeholder="备注"
              v-decorator="['remark', {rules: [{ required: false}], validateTrigger: ['change', 'blur']}]"
            />
          </a-form-item>

        </a-form>
      </a-modal>

      <!-- 编辑角色 -->
      <a-modal
        title="编辑角色"
        style="top: 20px;"
        :width="800"
        v-model="editVisible"
        @ok="handleOk($event, 'edit')"
      >
        <a-form class="permission-form" :form="form">
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="ID"
            hasFeedback
            validateStatus="success"
            hidden="hidden"
          >
            <a-input
              placeholder="ID"
              disabled="disabled"
              v-decorator="['id']"
            />
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="角色名称"
            hasFeedback
          >
            <a-input
              placeholder="角色名称"
              v-decorator="['name', {rules: [{ required: true, message: '角色名称为必填项' }], validateTrigger: ['change', 'blur']}]"
            />
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="角色别名"
            hasFeedback
          >
            <a-input
              placeholder="角色别名"
              v-decorator="['alias', {rules: [{ required: false }], validateTrigger: ['change', 'blur']}]"
            />
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="序号"
            hasFeedback
          >
            <a-input
              placeholder="序号"
              v-decorator="['sort', {rules: [{ required: false }], validateTrigger: ['change', 'blur']}]"
            />
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="状态"
            hasFeedback
          >
            <a-select v-decorator="['status', { initialValue: 1 }]">
              <a-select-option :value="1">正常</a-select-option>
              <a-select-option :value="2">禁用</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="备注"
            hasFeedback
          >
            <a-input
              placeholder="备注"
              v-decorator="['remark', {rules: [{ required: false}], validateTrigger: ['change', 'blur']}]"
            />
          </a-form-item>

        </a-form>
      </a-modal>

    </a-card>
  </page-header-wrapper>
</template>

<script>
import { STable } from '@/components'
import RoleModal from '../other/modules/RoleModal.vue'
import { getRolePageList, getRoleById, deleteRole, getSelectedMenuDetailById, createRole, updateRole } from '@/api/role'
import { labelCol, statusMap, wrapperCol } from '@/utils/constant'

export default {
  name: 'TableList',
  components: {
    STable,
    RoleModal
  },
  data () {
    return {
      description: '列表使用场景：后台管理中的权限管理以及角色管理，可用于基于 RBAC 设计的角色权限控制，颗粒度细到每一个操作类型。',

      editVisible: false,
      addVisible: false,

      labelCol: labelCol,
      wrapperCol: wrapperCol,
      form: this.$form.createForm(this),
      mdl: {},

      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头
      columns: [
        {
          title: '角色名称',
          dataIndex: 'name'
        },
        {
          title: '别名',
          dataIndex: 'alias'
        },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          scopedSlots: { customRender: 'createTime' },
          sorter: true
        }, {
          title: '操作',
          width: '150px',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      loadSingleData: (parameter) => {
        return getRoleById(parameter).then(res => {
          return res.data
        })
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const finalParameters = Object.assign(parameter, this.queryParam)
        return getRolePageList(finalParameters)
          .then(res => {
            return res.data
          })
      },

      expandedRowKeys: [],
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  filters: {
    statusFilter (key) {
      return statusMap[key].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    }
  },
  methods: {
    doAdd (values) {
      createRole(values).then(response => {
        if (response.code === 0) {
          this.$notification['success']({ message: '成功', description: '添加成功', duration: 4 })
          this.$refs.table.refresh()
        } else {
          this.$notification['error']({ message: '错误', description: response.msg, duration: 4 })
        }
        this.addVisible = false
      }).catch(err => {
        this.$notification['error']({ message: '错误', description: err, duration: 4 })
        this.addVisible = false
      })
    },
    doUpdate (values) {
      updateRole(values).then(response => {
        if (response.code === 0) {
          this.$notification['success']({ message: '成功', description: '修改成功', duration: 4 })
          this.$refs.table.refresh()
        } else {
          this.$notification['error']({ message: '错误', description: response.msg, duration: 4 })
        }
        this.editVisible = false
      }).catch(err => {
        this.$notification['error']({ message: '错误', description: err, duration: 4 })
        this.editVisible = false
      })
    },
    doDel (record) {
      deleteRole({
        ids: [record.id]
      }).then(response => {
        if (response.code === 0) {
          this.$notification['success']({ message: '成功', description: '删除成功', duration: 4 })
          this.$refs.table.refresh()
        } else {
          this.$notification['error']({ message: '错误', description: response.msg, duration: 4 })
        }
      }).catch(err => {
        this.$notification['error']({ message: '错误', description: err, duration: 4 })
      })
    },
    handleSearch () {
      this.$refs.table.refresh()
    },
    handleAdd (record) {
      this.addVisible = true
      console.log('record', record)
      this.$nextTick(() => {
        this.form.setFieldsValue(record)
      })
    },
    handleEdit (record) {
      this.editVisible = true
      console.log('record', record)
      this.$nextTick(() => {
        this.form.setFieldsValue(record)
      })
    },
    handleChangeStatus (record) {
      const that = this
      this.$model.confirm({
        title: '确定要' + (record.status === 1 ? '禁用' : '启用') + '么？',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          record.status = record.status === 1 ? 2 : 1
          that.doUpdate(record)
        },
        onCancel () {
        }
      })
    },
    handleDelete (record) {
      const that = this
      this.$model.confirm({
        title: '确定要删除么？',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          that.doDel(record)
        },
        onCancel () {
        }
      })
    },
    handleOk (e, type) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        console.log(err, values)

        if (type === 'add') {
          this.doAdd(values)
        } else if (type === 'edit') {
          this.doUpdate(values)
        }
      })
    },
    onChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    getMenuDetail (record, cb) {
      this.loading = true
      getSelectedMenuDetailById({ id: record.id }).then(res => {
        if (res.code === 0) {
          record.menus = res.data || []
          cb()
        } else {
          this.$notification['error']({ message: '错误', description: '获取菜单失败', duration: 4 })
        }
      }).finally(() => {
        this.loading = false
      })
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    }
  }
}
</script>
